/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.DesensitizedUtil.DesensitizedType;
import cn.hutool.core.util.ObjectUtil;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.ExceptionConstant;
import com.iwindplus.boot.domain.enums.SensitiveTypeEnum;
import com.iwindplus.boot.util.domain.dto.SensitiveDTO;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

/**
 * 脱敏相关工具类.
 *
 * @author zengdegui
 * @since 2025/04/19 00:40
 */
@Slf4j
public class SensitiveUtil {

    private SensitiveUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * 脱敏.
     *
     * @param data   待脱敏数据
     * @param config 脱敏配置
     * @return String
     */
    public static String desensitized(String data, SensitiveDTO config) {
        if (ObjectUtil.isEmpty(config.getType())) {
            return data;
        }
        if (SensitiveTypeEnum.CUSTOM.equals(config.getType())) {
            final int endExclude = data.length() - config.getEndReserve();
            // 自定义策略
            return CharSequenceUtil.hide(data, config.getStartInclude(), endExclude);
        } else {
            // 定义策略不为空，返回策略处理过的字符串
            DesensitizedType desensitizedType = SensitiveUtil.getDesensitizedType(config);
            if (Objects.nonNull(desensitizedType)) {
                return DesensitizedUtil.desensitized(data, desensitizedType);
            }
        }
        return data;
    }

    private static DesensitizedType getDesensitizedType(SensitiveDTO config) {
        DesensitizedType desensitizedType = null;
        try {
            desensitizedType = DesensitizedType.valueOf(config.getType().name());
        } catch (IllegalArgumentException ex) {
            log.error(ExceptionConstant.ILLEGAL_ARGUMENT_EXCEPTION, ex);
        }
        return desensitizedType;
    }

}
